package org.example;

import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

public class YamlValidator {

    // 1. 检查YAML文件格式是否合法
    public static boolean isYamlValid(File yamlFile) {
        try (InputStream input = new FileInputStream(yamlFile)) {
            new Yaml().load(input);
            return true;
        } catch (Exception e) {
            System.err.println("YAML格式错误: " + e.getMessage());
            return false;
        }
    }

    // 2. 检查必需字段是否存在
    public static boolean checkRequiredFields(File yamlFile, String[] requiredFields) {
        try (InputStream input = new FileInputStream(yamlFile)) {
            Map<String, Object> yamlMap = new Yaml().load(input);

            for (String field : requiredFields) {
                if (!yamlMap.containsKey(field)) {
                    System.err.println("缺少必需字段: " + field);
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            System.err.println("解析失败: " + e.getMessage());
            return false;
        }
    }

    // 3. 完整示例
    public static void main(String[] args) {
        File yamlFile = new File("map.yaml");

        // 检查1: YAML格式是否合法
        if (!isYamlValid(yamlFile)) {
            System.out.println("❌ YAML文件格式错误");
            return;
        }

        // 检查2: 必需字段是否存在
//        String[] requiredFields = {"name", "version", "author"};
//        if (!checkRequiredFields(yamlFile, requiredFields)) {
//            System.out.println("❌ 缺少必需字段");
//            return;
//        }

        System.out.println("✅ YAML文件完整且有效");
    }
}